﻿using System.Collections.Generic;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.SqlConnector;
using ApplicationLibrary;
using Fighter.Masters.ModuleData;
using System.Windows.Forms;
using System.Data;
using Fighter.Fights.ModuleData;

namespace Fighter.Masters.Forms
{
    public partial class Club : ApplicationLibrary.DBManager.DocumentForm
    {
        RRFight rRFight = null;
        RRAthleteForClub rRAthleteForClub = null;
        DRAthlete dRAthlete = null;

        public Club()
            : base(Properties.Resources.F_Club)
        {
            InitializeComponent();
            keyControl = txtClub;
        }

        #region Virtual Method

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarClubParam(txtClub.Text);
        }

        protected override void OnAttachData()
        {
            dbManager = new dbmanagerClub("ClubForm", new RadarClub(), this);
            dbManager.AddMaster(this, FG_Club.Name, true);
            dbManager.AddSlave(FG_Coach.Name, true);
            dbManager.AddRelation("Coach", FG_Club.Mail, FG_Coach.Mail, false);
            dbManager.AddSlave(FG_Athlete.Name, false);
            dbManager.AddRelation("Athlete", FG_Club.Mail, FG_Athlete.Mail, false);
            dbManager.AddSlave(FG_Registration.Name, true);
            dbManager.AddRelation("Registration", FG_Club.Mail, FG_Registration.Mail, false);

            cbbCountry.AttachDataReader<int>(new RRDesctiptionType(DescriptionType.E_Regions), FG_Descriptions.ID, FG_Descriptions.Description, true);

            dbManager.Dataset.Tables[FG_Registration.Name].Columns.Add(new DataColumn(FG_Registration.AthleteName.Name, typeof(string)));

            dgwAthlete.AddReadOnlyColumn(FG_Athlete.FirstName, true);

            rRFight = new RRFight();
            rRAthleteForClub = new RRAthleteForClub();
            dRAthlete = new DRAthlete();

            if (rRFight.Find())
                ((dbmanagerClub)dbManager).FightID = rRFight.GetValue<int>(FG_Fight.ID);
        }

        protected override void OnBindData()
        {
            BindControl(txtClub, FG_Club.Club);
            BindControl(txtCity, FG_Club.City);
            BindControl(txtMail, FG_Club.Mail);
            BindControl(cbbCountry, FG_Club.Region, "SelectedValue", NullValue.NotSet);
            BindControl(txtPhone, FG_Club.Phone);

            dgwCoach.AutoGenerateColumns = false;
            dgwCoach.DataSource = dbManager.SlaveBinding("Coach");
            dgwCoach.RowIndex = FG_Coach.Line;

            BindColumn(clc_Line, FG_Coach.Line);
            BindColumn(clc_FirstName, FG_Coach.FirstName);
            BindColumn(clc_Phone, FG_Coach.Phone);

            BindControl(dgwCoach);

            dgwAthlete.AutoGenerateColumns = false;
            dgwAthlete.DataSource = dbManager.SlaveBinding("Athlete");

            BindColumn(cla_Mail, FG_Athlete.Mail);
            BindColumn(cla_ID, FG_Athlete.ID);
            BindColumn(cla_Name, FG_Athlete.FirstName);

            BindControl(dgwAthlete);

            dgwFight.AutoGenerateColumns = false;
            dgwFight.DataSource = dbManager.SlaveBinding("Registration");

            BindColumn(clf_Mail, FG_Registration.Mail);
            BindColumn(clf_Athlete, FG_Registration.Athlete);
            BindColumn(clf_Fight, FG_Registration.Fight);
            BindColumn(clf_AthleteName, FG_Registration.AthleteName);

            BindColumn(clf_ChausLight, FG_Registration.ChausLight);
            BindColumn(clf_SavateAss, FG_Registration.SavateAss);
            BindColumn(clf_PointFight, FG_Registration.PointFight);
            BindColumn(clf_LightContact, FG_Registration.LightContact);
            BindColumn(clf_KickLight, FG_Registration.KickLight);
            BindColumn(clf_K1Light, FG_Registration.K1Light);
            BindColumn(clf_ThaiLight, FG_Registration.ThaiLight);
            BindColumn(clf_MMALight, FG_Registration.MmaLight);
            BindColumn(clf_Grapling, FG_Registration.Grapling);

            BindColumn(clf_ChaussCombact, FG_Registration.ChaussCombact);
            BindColumn(clf_SavateCombact, FG_Registration.SavateCombact);
            BindColumn(clf_FullContact, FG_Registration.FullContact);
            BindColumn(clf_LowKick, FG_Registration.LowKick);
            BindColumn(clf_K1Rules, FG_Registration.K1Rules);
            BindColumn(clf_ThaiFull, FG_Registration.ThaiFull);
            BindColumn(clf_MMAFull, FG_Registration.MMAFull);

            BindColumn(clf_Checked, FG_Registration.Checked);

            BindControl(dgwFight);
        }

        protected override void FocusOnNew()
        {
            txtClub.Focus();
        }

        protected override void OnDisableControlsForEdit()
        {
            txtMail.Enabled = false;
            CreateRegistrationRow();
        }

        protected override bool OnBeforeSave()
        {
            if (txtMail.Text.IsEmpty())
            {
                MyMessageBox(this, Properties.Resources.M_Warning, Properties.Resources.M_MissingMail, MessageBoxButtons.OK, MessageBoxIcon.Warning );
                return false;
            }

            return base.OnBeforeSave();
        }

        protected override void OnPrepareAuxData()
        {
            for (int t = 0; t < dgwFight.Rows.Count; t++)
            {
                DataGridViewRow dgv = dgwFight.Rows[t];
                if (dRAthlete.Find(DataGridViewRowValues.GetValue<int>(dgv, FG_Registration.Athlete)))
                    DataGridViewRowValues.SetValue<string>(dgv, FG_Registration.AthleteName, dRAthlete.GetValue<string>(FG_Athlete.FirstName));
            }

            base.OnPrepareAuxData();
        }

        #endregion

        private bool CreateRegistrationRow()
        {
            if (rRFight.Find())
            {
                for (int t = 0; t < rRFight.Count; t++)
                {
                    int fightID = rRFight.GetValue<int>(FG_Fight.ID, t);
                    string fightDesc = rRFight.GetValue<string>(FG_Fight.Description, t);

                    if (rRAthleteForClub.Find(txtMail.Text))
                    {
                        for (int i=0; i<rRAthleteForClub.Count; i++)
                        {
                            int athleteID = rRAthleteForClub.GetValue<int>(FG_Athlete.ID, i);
                            string athleteDesc = rRAthleteForClub.GetValue<string>(FG_Athlete.FirstName, i);

                            AddRegistrationRow(fightID, fightDesc, athleteID, athleteDesc);
                        }
                    }
                }
            }

            return true;
        }
        private void AddRegistrationRow(int fightID,string fightDesc,int athleteID,string athleteDesc)
        {
 	        for (int t=0; t< dgwFight.Rows.Count;t++)
            {
                DataGridViewRow dgv = dgwFight.Rows[t];
                if (
                    DataGridViewRowValues.GetValue<int>(dgv, FG_Registration.Athlete) == athleteID &&
                    DataGridViewRowValues.GetValue<int>(dgv, FG_Registration.Fight) == fightID
                    )
                    return;
            }
 
            DataRowView drv =  dgwFight.AddNewRow();
            DataRowViewValues.SetValue<string>(drv, FG_Registration.Mail, txtMail.Text);
            DataRowViewValues.SetValue<int>(drv, FG_Registration.Athlete, athleteID);
            DataRowViewValues.SetValue<int>(drv, FG_Registration.Fight, fightID);

            DataRowViewValues.SetValue<bool>(drv, FG_Registration.ChausLight, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.SavateAss, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.PointFight, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.LightContact, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.KickLight, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.K1Light, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.ThaiLight, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.MmaLight, false);

            DataRowViewValues.SetValue<bool>(drv, FG_Registration.ChaussCombact, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.SavateCombact, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.FullContact, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.LowKick, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.K1Rules, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.ThaiFull, false);
            DataRowViewValues.SetValue<bool>(drv, FG_Registration.MMAFull, false);
            DataRowViewValues.SetValue<string>(drv, FG_Registration.AthleteName, athleteDesc);
        }
    }


    #region DbManager dbmanagerClub

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    internal class dbmanagerClub : DBManager
    {
        public int FightID { get; set; }
        public dbmanagerClub(string name, RadarForm radar, DocumentForm document)
            : base(name, radar, document)
        { }

        protected override void dAdapter_MasterRowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            base.dAdapter_MasterRowUpdating(sender, e);
        }

        protected override void dAdapter_RowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                if (e.Row.Table.ToString() == FG_Coach.Name)
                    e.Row[FG_Coach.Mail.Name] = GetColumn<string>(FG_Club.Mail, Pos);
            }
            base.dAdapter_RowUpdating(sender, e);
        }

        protected override string CreateMasterQuery()
        {
            this.Table = new FG_Club();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(this.Table);
            qB.AddCompare(FG_Club.Mail, "@p1");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter sParam = new SqlABParameter("@p1", FG_Club.Mail);
            sParam.Value = FG_Club.Mail.DefaultValue;
            PList.Add(sParam);
            return PList;
        }

        protected override List<SqlABParameter> CreateSlaveParam(string name)
        {
            if (name == FG_Coach.Name)
            {
                List<SqlABParameter> PList = new List<SqlABParameter>();

                SqlABParameter sParam = new SqlABParameter("@p2", FG_Coach.Mail);
                sParam.Value = "";
                PList.Add(sParam);
                return PList;
            }

            if (name == FG_Athlete.Name)
            {
                List<SqlABParameter> PList = new List<SqlABParameter>();

                SqlABParameter sParam1 = new SqlABParameter("@p3", FG_Athlete.Mail);
                sParam1.Value = "";
                PList.Add(sParam1);

                return PList;
            }

            if (name == FG_Registration.Name)
            {
                List<SqlABParameter> PList = new List<SqlABParameter>();

                SqlABParameter sParam1 = new SqlABParameter("@p4", FG_Registration.Mail);
                sParam1.Value = "";
                PList.Add(sParam1);

                SqlABParameter sParam2 = new SqlABParameter("@p5", FG_Registration.Fight);
                sParam1.Value = 0;
                PList.Add(sParam2);

                return PList;
            }

            return null;
        }

        protected override string CreateSlaveQuery(string name)
        {
            if (name == FG_Coach.Name)
            {
                QueryBuilder qB = new QueryBuilder();
                qB.AddSelect();
                qB.AddFrom(FG_Coach.Name);
                qB.AddCompare(FG_Coach.Mail, "@p2");
                qB.AddOrder(FG_Coach.Line);
                return qB.Query;
            }

            if (name == FG_Athlete.Name)
            {
                QueryBuilder qB = new QueryBuilder();
                qB.AddSelect();
                qB.AddFrom(FG_Athlete.Name);
                qB.AddCompare(FG_Athlete.Mail, "@p3");
                qB.AddOrder(FG_Athlete.FirstName);
                return qB.Query;
            }

            if (name == FG_Registration.Name)
            {
                QueryBuilder qB = new QueryBuilder();
                qB.AddSelect();
                qB.AddFrom(FG_Registration.Name);
                qB.AddCompare(FG_Registration.Mail, "@p4");
                qB.AddCompare(FG_Registration.Fight, "@p5");
                return qB.Query;
            }

            return "";
        }

        protected override void SetParameters(ApplicationLibrary.ExtendedControls.IRadarParameters key, DBCollection collection)
        {
            collection.Parameter[0].Value = key[0];
            if (collection.Name == FG_Registration.Name)
                collection.Parameter[1].Value = FightID;

        }
    }

    #endregion
}